# -*- coding: utf-8 -*-
"""
Created on Sun Oct 11 10:09:35 2020
用于双量子点量子模型
单量子比特的归零操作
多个初始态对多个目标态的归零保真度
选用两种策略：
先采用 要么最优，要么最差
如果效果不好就选第二种
动作要么选最优的，要么选次优的

@author: Waikikilick
"""

import numpy as np
from scipy.linalg import expm
from time import *
import multiprocessing as mp
np.random.seed(1)
sx = np.mat([[0, 1], [1, 0]], dtype=complex) 
sz = np.mat([[1, 0], [0, -1]], dtype=complex)
action_space = np.array([0,1,2,3])#,5,6,7,8])
# a0,a1,a2,a3,a4,a5,a6,a7,a8 = 0,0,0 ,0,0,0,0,0,0 #统计各动作被选用的频率

# target_psi = np.mat([[1], [0]], dtype=complex)
# target_psi = np.mat([[1], [1]], dtype=complex)/np.sqrt(2)

theta_num = 6 #除了 0 和 Pi 两个点之外，点的数量
varphi_num = 21#varphi 角度一圈上的点数
#总点数为 theta_num * varphi_num + 2(布洛赫球两极)

theta = np.linspace(0,np.pi,theta_num+2,endpoint=True) 
varphi = np.linspace(0,np.pi*2,varphi_num,endpoint=False) 

def psi_set():
    psi_set = []
    for ii in range(1,theta_num+1):
        for jj in range(varphi_num):
            psi_set.append(np.mat([[np.cos(theta[ii]/2)],[np.sin(theta[ii]/2)*(np.cos(varphi[jj])+np.sin(varphi[jj])*(0+1j))]]))
    psi_set.append(np.mat([[1], [0]], dtype=complex))
    psi_set.append(np.mat([[0], [1]], dtype=complex))
    return psi_set
#----------------------------------------------------------------------------------------------------
#动作直接选最优的
def step(psi,target_psi,F):
    fid_list = []
    psi_list = []
    action_list = list(range(len(action_space)))
    for action in action_list:
        
        H = float(action_space[action])* sz + 1 * sx
        U = expm(-1j * H * dt) 
        psi_ = U * psi
        fid = (np.abs(psi_.H * target_psi) ** 2).item(0).real 
        
        psi_list.append(psi_)
        fid_list.append(fid)
        best_action = fid_list.index(max(fid_list))
        best_fid = max(fid_list)
    psi_ = psi_list[best_action]
    # print(best_action)
    return best_action, best_fid, psi_

#动作选最优的，或者最差的
def step1(psi,target_psi,F):
    fid_list = []
    psi_list = []
    action_list = list(range(len(action_space)))
    for action in action_list:
        
        H = float(action_space[action])* sz + 1 * sx
        U = expm(-1j * H * dt) 
        psi_ = U * psi
        fid = (np.abs(psi_.H * target_psi) ** 2).item(0).real 
        
        psi_list.append(psi_)
        fid_list.append(fid)
    
    if F < max(fid_list):
        best_action = fid_list.index(max(fid_list))
        best_fid = max(fid_list)
    else:
        # del action_list[fid_list.index(max(fid_list))]
        # del psi_list[fid_list.index(max(fid_list))]
        # del fid_list[fid_list.index(max(fid_list))]
        
        # best_action = fid_list.index(max(fid_list))
        # best_fid = max(fid_list)
        
        best_action = fid_list.index(min(fid_list))
        best_fid = min(fid_list)
    psi_ = psi_list[best_action]
    # print(best_action)
    return best_action, best_fid, psi_

#动作选最优的，或者次优的
def step2(psi,target_psi,F):
    fid_list = []
    psi_list = []
    action_list = list(range(len(action_space)))
    for action in action_list:
        
        H = float(action_space[action])* sz + 1 * sx
        U = expm(-1j * H * dt) 
        psi_ = U * psi
        fid = (np.abs(psi_.H * target_psi) ** 2).item(0).real 
        
        psi_list.append(psi_)
        fid_list.append(fid)
        
    if F < max(fid_list):
        best_action = fid_list.index(max(fid_list))
        best_fid = max(fid_list)
    else:
        del action_list[fid_list.index(max(fid_list))]
        del psi_list[fid_list.index(max(fid_list))]
        del fid_list[fid_list.index(max(fid_list))]
        
        best_action = fid_list.index(max(fid_list))
        best_fid = max(fid_list)
        
        # best_action = fid_list.index(min(fid_list))
        # best_fid = min(fid_list)
    psi_ = psi_list[best_action]
    # print(best_action)
    return best_action, best_fid, psi_
#---------------------------------------------------------------------------------
#将测试集的保真度从小到大排列出来，来展示保真度分布
def sort_fid(test_fidelity_list):
    sort_fid = []
    for i in range (test_fidelity_list.shape[0]):
        b = test_fidelity_list[i,:]
        sort_fid  = np.append(sort_fid,b)
    sort_fid.sort()
    return sort_fid
#--------------------------------------------------------------------------------


def job(target_psi):
    fid_list = []
    for psi1 in init_set:
        
        psi = psi1
        F = (np.abs(psi1.H * target_psi) ** 2).item(0).real 
        fid_max = 0
        fid_max1 = 0
        fid_max2 = 0
        fid_max0 = 0
        step_n = 0
        while True:
            action, F, psi_ = step1(psi,target_psi,F)
            fid_max1 = max(F,fid_max1)
            psi = psi_
            step_n += 1
            if fid_max1>0.999 or step_n>step_max:
                break
            
        step_n = 0
        F = (np.abs(psi1.H * target_psi) ** 2).item(0).real 
        psi = psi1
        while True:
            action, F, psi_ = step2(psi,target_psi,F)
            fid_max2 = max(F,fid_max2)
            psi = psi_
            step_n += 1
            if fid_max2>0.999 or step_n>step_max:
                break 
            
        fid_max = max(fid_max1,fid_max2)
        if fid_max < 0.99:
            step_n = 0
            F = (np.abs(psi1.H * target_psi) ** 2).item(0).real 
            psi = psi1
            while True:
                action, F, psi_ = step(psi,target_psi,F)
                fid_max0 = max(F,fid_max0)
                psi = psi_
                step_n += 1
                if fid_max0>0.999 or step_n>step_max:
                    break 
            fid_max = max(fid_max,fid_max0)  
        fid_list.append(fid_max)
    return  np.mean(fid_list)

def multicore():
    pool = mp.Pool()
    F_list = pool.map(job, target_set)
    return F_list
    

if __name__ == '__main__':
    target_set = psi_set()
    target_set = target_set[68:73]+target_set[89:94]# A area 0.9018504159122663
    # target_set = target_set[36:40]+target_set[57:61]# B area 0.8862742472629985
    # print(target_set)
    init_set = psi_set()
    # print(target_set)
    time1 = time()
    for kT in [1,2,3,4,5,6,7,8,9,10]:
        for kdt in [2,3,4,5,6,7,8,9,10]:
            F_list = []
            T = kT*np.pi
            dt = np.pi/kdt
            step_max = T/dt
            F_list = multicore()
            print("kT = ",kT,"kdt = ",kdt,"mean_fid = ",np.mean(F_list))
    time2 = time()
    print('time_cost is: ',time2-time1)

#目标点集
# [matrix([[0.92387953+0.j],
#          [0.38268343+0.j]]),
#  matrix([[0.92387953+0.j        ],
#          [0.27059805+0.27059805j]]),
#  matrix([[9.23879533e-01+0.j        ],
#          [2.34326020e-17+0.38268343j]]),
#  matrix([[ 0.92387953+0.j        ],
#          [-0.27059805+0.27059805j]]),
#  matrix([[ 0.92387953+0.00000000e+00j],
#          [-0.38268343+4.68652041e-17j]]),
#  matrix([[ 0.92387953+0.j        ],
#          [-0.27059805-0.27059805j]]),
#  matrix([[ 9.23879533e-01+0.j        ],
#          [-7.02978061e-17-0.38268343j]]),
#  matrix([[0.92387953+0.j        ],
#          [0.27059805-0.27059805j]]),
#  matrix([[0.70710678+0.j],
#          [0.70710678+0.j]]),
#  matrix([[0.70710678+0.j ],
#          [0.5       +0.5j]]),
#  matrix([[7.07106781e-01+0.j        ],
#          [4.32978028e-17+0.70710678j]]),
#  matrix([[ 0.70710678+0.j ],
#          [-0.5       +0.5j]]),
#  matrix([[ 0.70710678+0.00000000e+00j],
#          [-0.70710678+8.65956056e-17j]]),
#  matrix([[ 0.70710678+0.j ],
#          [-0.5       -0.5j]]),
#  matrix([[ 7.07106781e-01+0.j        ],
#          [-1.29893408e-16-0.70710678j]]),
#  matrix([[0.70710678+0.j ],
#          [0.5       -0.5j]]),
#  matrix([[0.38268343+0.j],
#          [0.92387953+0.j]]),
#  matrix([[0.38268343+0.j        ],
#          [0.65328148+0.65328148j]]),
#  matrix([[3.82683432e-01+0.j        ],
#          [5.65713056e-17+0.92387953j]]),
#  matrix([[ 0.38268343+0.j        ],
#          [-0.65328148+0.65328148j]]),
#  matrix([[ 0.38268343+0.00000000e+00j],
#          [-0.92387953+1.13142611e-16j]]),
#  matrix([[ 0.38268343+0.j        ],
#          [-0.65328148-0.65328148j]]),
#  matrix([[ 3.82683432e-01+0.j        ],
#          [-1.69713917e-16-0.92387953j]]),
#  matrix([[0.38268343+0.j        ],
#          [0.65328148-0.65328148j]]),
#  matrix([[1.+0.j],
#          [0.+0.j]]),
#  matrix([[0.+0.j],
#          [1.+0.j]])]

# kT =  1 kdt =  2 mean_fid =  0.9308070179760513
# kT =  1 kdt =  3 mean_fid =  0.9307337210303832
# kT =  1 kdt =  5 mean_fid =  0.9606670576330517
# kT =  1 kdt =  10 mean_fid =  0.9509168163505988
# kT =  1 kdt =  20 mean_fid =  0.9462430371064627
# kT =  1 kdt =  30 mean_fid =  0.9447877523930877
# kT =  1 kdt =  40 mean_fid =  0.9420035646995455
# kT =  2 kdt =  2 mean_fid =  0.9625678240863695
# kT =  2 kdt =  3 mean_fid =  0.9627791376840196
# kT =  2 kdt =  5 mean_fid =  0.9725647765967409
# kT =  2 kdt =  10 mean_fid =  0.960905616604987
# kT =  2 kdt =  20 mean_fid =  0.9511107151818115
# kT =  2 kdt =  30 mean_fid =  0.9495536883528242
# kT =  2 kdt =  40 mean_fid =  0.9460677245405374
# kT =  3 kdt =  2 mean_fid =  0.9737887662256963
# kT =  3 kdt =  3 mean_fid =  0.9768511224734105
# kT =  3 kdt =  5 mean_fid =  0.9772345031399998
# kT =  3 kdt =  10 mean_fid =  0.9651532020997583
# kT =  3 kdt =  20 mean_fid =  0.9526477250629523
# kT =  3 kdt =  30 mean_fid =  0.9511027472299977
# kT =  3 kdt =  40 mean_fid =  0.9474056952318806
# kT =  4 kdt =  2 mean_fid =  0.97874008440973
# kT =  4 kdt =  3 mean_fid =  0.9833467583837318
# kT =  4 kdt =  5 mean_fid =  0.9798090326160704
# kT =  4 kdt =  10 mean_fid =  0.967590520318196
# kT =  4 kdt =  20 mean_fid =  0.9535085139769521
# kT =  4 kdt =  30 mean_fid =  0.9519599454066283
# kT =  4 kdt =  40 mean_fid =  0.9480190649962066
# time_cost is:  1136.1673998832703
